package com.tanhua.dubbo.api;


import com.tanhua.model.mongo.TestPaper;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.PaperVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@DubboService
public class TestPaperApiImpl implements TestPaperApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public Map<String, TestPaper> findByIds(List<String> paperId) {
        Map<String, TestPaper> map=new HashMap<>();
        for (String id : paperId) {
            TestPaper paper = mongoTemplate.findById(new ObjectId(id), TestPaper.class);
            map.put(id,paper);
        }
        return map;

    }

    @Override
    public List<TestPaper> findAll() {
        List<TestPaper> list = mongoTemplate.findAll(TestPaper.class);
        return list;
    }

    @Override
    public PageResult findByPage(Integer page, Integer pageSize) {
        Query query=new Query();
        long count = mongoTemplate.count(query, TestPaper.class);
        query.with(Sort.by(Sort.Order.asc("star")))
                .skip((page-1)*pageSize)
                .limit(pageSize);
        List<TestPaper> list = mongoTemplate.find(query, TestPaper.class);
        List<PaperVo> vos=new ArrayList<>();
        for (TestPaper paper : list) {
            PaperVo init = PaperVo.init(paper);
            vos.add(init);
        }
        return new PageResult(page,pageSize,count,vos);
    }

    @Override
    public void delete(String id) {
        Criteria criteria = Criteria.where("id").is(new ObjectId(id));
        Query query = Query.query(criteria);
        mongoTemplate.remove(query,TestPaper.class);
    }

    @Override
    public TestPaper findById(String id) {
        TestPaper paper = mongoTemplate.findById(new ObjectId(id), TestPaper.class);
        return paper;
    }

    @Override
    public void save(TestPaper papers) {
        mongoTemplate.save(papers);
    }

    @Override
    public void update(TestPaper paper,String paperId) {
        Criteria criteria = Criteria.where("id").is(new ObjectId(paperId));
        Query query = Query.query(criteria);
        Update update=new Update();
        update.set("name",paper.getName());
        update.set("cover",paper.getCover());
        update.set("level",paper.getLevel());
        update.set("star",paper.getStar());
        mongoTemplate.updateFirst(query,update,TestPaper.class);
    }
}
